﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarsWebApplication.businesslogic.utils;
using bg.krasi.caroffers;
using CarsWebApplication.businesslogic.entities;
using System.Web.Configuration;
using CarsWebApplication.businesslogic.constants;
using CarsWebApplication.service.currency;

public partial class AddOffer : System.Web.UI.Page
{
    MobileOffersService mobileOffersService;
    //private CurrencyConvertorSoapClient currencyConvertorService;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.mobileOffersService == null)
        {
            this.mobileOffersService = new MobileOffersService();
            CarWebAppUtility.SetMobileOffersWSUrl(this.mobileOffersService);
        }
        /*
        if (this.currencyConvertorService == null)
        {
            this.currencyConvertorService = new CurrencyConvertorSoapClient("CurrencyConvertorSoap12");
        }
         */ 
        if (IsPostBack == false)
        {
            string allBrands = mobileOffersService.getAllBrands();
            List<Brand> brands = CarWebAppUtility.GetBrands(allBrands);
            this.brandsDropDown.DataSource = brands;
            this.brandsDropDown.DataBind();
            //this.currencyRate.Text = this.currencyConvertorService.ConversionRate(Currency.USD, Currency.EUR).ToString();
            this.currencies.DataSource = Enum.GetValues(typeof(Currency));
            this.currencies.DataBind();
            this.currencies.SelectedValue = Currency.USD.ToString();
        }
    }

    protected void Brands_IndexChanged(object sender, EventArgs e)
    {
        string brandIdTxt = this.brandsDropDown.SelectedValue;
        int brandId;
        if (Int32.TryParse(brandIdTxt, out brandId))
        {
            if (brandId >= 0)
            {
                string modelsByBrand = this.mobileOffersService.getModelsByBrand(brandId);
                if (string.IsNullOrEmpty(modelsByBrand) == false)
                {
                    List<Model> models = CarWebAppUtility.GetModels(modelsByBrand);
                    this.modelsDropDown.DataSource = models;
                    this.modelsDropDown.DataBind();
                }
            }
        }
    }

    protected void Currencies_IndexChanged(object sender, EventArgs e)
    {
        string currencyTxt = this.currencies.SelectedValue;
        string usdCurrency = Currency.USD.ToString();
        string convertedCurrency;
        if (currencyTxt.Equals(usdCurrency) == false)
        {
            string priceValue = this.priceTxt.Text;
            if (string.IsNullOrEmpty(priceValue))
            {
                convertedCurrency = string.Empty;
            }
            else
            {
                try
                {
                    string addressTemplate = WebConfigurationManager.AppSettings[CarWebAppConstants.CURRENCY_CONVERTER_REST_URL_CONFIG_KEY];
                    string uriWithData = string.Format(addressTemplate, priceValue, usdCurrency, currencyTxt);
                    string responseSource;
                    if (HttpUtility.GetResponseSource(uriWithData, out responseSource))
                    {
                        convertedCurrency = responseSource;
                    }
                    else
                    {
                        convertedCurrency = "Could not retrieve converted currency";
                    }
                }
                catch (Exception exception)
                {
                    convertedCurrency = "Currency converter error: '" + exception.Message + "'";
                }
            }
        }
        else
        {
            convertedCurrency = "Please choose different currency";
        }
        this.currencyInfo.Text = convertedCurrency;
    }

    protected void Cancel_OnClick(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }

    protected void SaveOffer_OnClick(object sender, EventArgs e)
    {
        if (Page.IsValid == false)
        {
            return;
        }
        string brandIdTxt = this.brandsDropDown.SelectedValue;
        int brandId;
        bool validBrandId = Int32.TryParse(brandIdTxt, out brandId);
        string modelIdTxt = this.modelsDropDown.SelectedValue;
        int modelId;
        bool validModelId = Int32.TryParse(modelIdTxt, out modelId);
        string makeYearTxt = this.makeYear.Text;
        int year;
        bool validYear = Int32.TryParse(makeYearTxt, out year);
        string priceTxt = this.priceTxt.Text;
        double price;
        bool validPrice = Double.TryParse(priceTxt, out price);
        string contact = this.contact.Text;
        if (validBrandId && validModelId && validYear && validPrice)
        {
            this.mobileOffersService.insertOffer(brandId, modelId, year, price, contact);
            ListItem positiveMsg = new ListItem("Offer is saved successfully");
            this.notificationMsgList.Items.Clear();
            this.notificationMsgList.Items.Add(positiveMsg);
            this.notificationMsgPanel.CssClass = "positiveMsg";
            this.notificationMsgPanel.Visible = true;
        }
    }

    protected void MakeYear_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        int year;
        e.IsValid = CarWebAppUtility.IsValidYear(e.Value, out year);
    }

    protected void Price_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        double year;
        e.IsValid = CarWebAppUtility.IsValidPrice(e.Value, out year);
    }

    protected void Model_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        int modelId;
        string modelIdTxt = e.Value;
        if (Int32.TryParse(modelIdTxt, out modelId) && modelId >= 0)
        {
            e.IsValid = true;
        }
        else
        {
            e.IsValid = false;
        }
    }

    protected void Brand_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        int brandId;
        string brandIdTxt = e.Value;
        if (Int32.TryParse(brandIdTxt, out brandId) && brandId >= 0)
        {
            e.IsValid = true;
        }
        else
        {
            e.IsValid = false;
        }
    }

    protected void Contact_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        string email = e.Value;
        string responseSource;
        string emailValidationErrorMsg = string.Empty;
        this.notificationMsgList.Items.Clear();
        try
        {
            string mailValidatorUriTemplate = WebConfigurationManager.AppSettings[CarWebAppConstants.MAIL_VALIDATOR_REST_URL_CONFIG_KEY];
            string uri = string.Format(mailValidatorUriTemplate, email);
            if (HttpUtility.GetResponseSource(uri, out responseSource))
            {
                if (string.IsNullOrEmpty(responseSource) == false)
                {
                    if (responseSource.Contains("OK"))
                    {
                        e.IsValid = true;                        
                        this.notificationMsgPanel.Visible = false;
                        return;
                    }
                    else
                    {
                        emailValidationErrorMsg = responseSource;
                    }
                }
                else
                {
                    emailValidationErrorMsg = "Email validator returns empty response";
                }
            }
            else
            {
                emailValidationErrorMsg = "Error retrieving response form email validator";
            }
        }
        catch (Exception exception)
        {
            emailValidationErrorMsg = "Email validation exception: " + exception.Message;
        }
        ListItem emailValidationErrorItem = new ListItem(emailValidationErrorMsg);
        this.notificationMsgList.Items.Add(emailValidationErrorItem);
        this.notificationMsgPanel.CssClass = "negativeMsg";
        this.notificationMsgPanel.Visible = true;
        e.IsValid = false;
    }
    
}